package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func main() {
	db, cache := initDB()
	if db == nil || cache == nil {
		panic("数据库初始化错误")
		return
	}
	r := gin.Default()
	r.POST("/login", func(c *gin.Context) {
		var login Login
		err := c.BindJSON(&login)
		if err != nil {
			c.JSON(200, &Result{
				Code: 400,
				Data: "数据格式错误",
			})
		} else {
			res := userLogin(login, db, cache)
			c.JSON(200, res)
		}
	})
	r.POST("/organ/register", func(c *gin.Context) {
		var organ OrgRegData
		err := c.BindJSON(&organ)
		if err != nil {
			c.JSON(200, &Result{
				Code: 400,
				Data: "数据格式错误",
			})
		} else {
			res := OrganRegister(organ, db)
			c.JSON(200, res)
		}
	})
	r.POST("/user/register", func(c *gin.Context) {
		var user User
		err := c.BindJSON(&user)
		if err != nil {
			c.JSON(200, &Result{
				Code: 400,
				Data: "数据格式错误",
			})
		} else {
			res := UserRegister(&user, db)
			c.JSON(200, res)
		}
	})
	r.POST("/get/vote/all", func(c *gin.Context) {
		token := c.PostForm("token")
		if token == "" {
			c.JSON(200, &Result{
				Code: 400,
				Data: "token无效",
			})
		} else {
			res := getAllVoteImp(token, db, cache)
			c.JSON(200, res)
		}
	})
	r.POST("/get/vote", func(c *gin.Context) {
		id := c.PostForm("id")
		v := getVoteImp(id, db)
		c.JSON(200, *v)
	})
	r.POST("/vote", func(c *gin.Context) {
		var do DoVote
		err := c.BindJSON(&do)
		if err != nil {
			c.JSON(200, &Result{
				Code: 400,
				Data: "数据格式错误",
			})
		} else {
			res := doVoteImp(do, db, cache)
			c.JSON(200, res)
		}
	})
	r.POST("/create/vote", func(c *gin.Context) {
		do := struct {
			Token string `json:"token"`
			V     Vote   `json:"vote"`
		}{"", Vote{}}
		err := c.BindJSON(&do)
		if err != nil {
			fmt.Println(err)
			c.JSON(200, &Result{
				Code: 400,
				Data: "数据格式错误",
			})
		} else {
			res := createVoteImp(do.Token, do.V, db, cache)
			c.JSON(200, res)
		}
	})
	r.POST("/change", func(c *gin.Context) {
		var data struct {
			User   Login  `json:"user"`
			NewPsw string `json:"newPsw"`
		}
		err := c.BindJSON(&data)
		if err != nil {
			c.JSON(200, &Result{
				Code: 400,
				Data: "数据格式错误",
			})
		} else {
			res := changePassword(data.NewPsw, data.User, db, cache)
			c.JSON(200, res)
		}
	})
	r.POST("/get/user/count", func(c *gin.Context) {
		id := c.PostForm("id")
		c.JSON(200, getUserCount(id, db))
	})
	r.POST("/get/vote/count", func(c *gin.Context) {
		id := c.PostForm("id")
		c.JSON(200, getVoteCount(id, db))
	})
	r.POST("/logout", func(c *gin.Context) {
		token := c.PostForm("token")
		cache.Delete("token_" + token)
		c.JSON(200, &Result{
			Code: 200,
			Data: "退出登录成功！",
		})
	})
	r.POST("/get/organ", func(c *gin.Context) {
		id := c.PostForm("id")
		o := getOrganByIdImp(id, db)
		c.JSON(200, o)
	})
	r.POST("/get/organ/all", func(c *gin.Context) {
		organs := getAllOrganImp(db)
		c.JSON(200, organs)
	})
	r.Run(":801")
}
